﻿using UnityEngine;
using UnityEngine.UI;

[DisallowMultipleComponent]
[RequireComponent(typeof(GridLayoutGroup))]
public class CenterOnChild : MonoBehaviour
{
    RectTransform rtf;
    ScrollRect scroll;

    void Awake()
    {
        scroll = GetComponentInParent<ScrollRect>();
        rtf = GetComponent<RectTransform>();
    }

    public void CenterOnItem(RectTransform target)
    {
        Vector3 itemCurrentLocalPos = rtf.InverseTransformVector(ConvertLocalPosToWorldPos(target));
        Vector3 itemTargetLocalPos = rtf.InverseTransformVector(ConvertLocalPosToWorldPos(scroll.viewport));

        Vector3 diff = itemTargetLocalPos - itemCurrentLocalPos;
        diff.z = 0.0f;

        float x = scroll.content.rect.width - scroll.viewport.rect.width;
        float y = scroll.content.rect.height - scroll.viewport.rect.height;
        var newNormalizedPosition = new Vector2(diff.x / x, diff.y / y);

        newNormalizedPosition = scroll.normalizedPosition - newNormalizedPosition;
        newNormalizedPosition.x = Mathf.Clamp01(newNormalizedPosition.x);
        newNormalizedPosition.y = Mathf.Clamp01(newNormalizedPosition.y);
        scroll.normalizedPosition = newNormalizedPosition;
    }

    private Vector3 ConvertLocalPosToWorldPos(RectTransform target)
    {
        var pivotOffset = new Vector3(
            (0.5f - target.pivot.x) * target.rect.size.x,
            (0.5f - target.pivot.y) * target.rect.size.y, 0f);

        var localPos = target.localPosition + pivotOffset;
        return target.parent.TransformPoint(localPos);
    }
}